package com.suqiu.qqrobot.config;

import com.suqiu.qqrobot.config.properties.OkHttpProperties;
import com.suqiu.qqrobot.config.properties.OpenAiProperties;
import com.unfbx.chatgpt.OpenAiClient;
import com.unfbx.chatgpt.interceptor.OpenAILogger;
import com.unfbx.chatgpt.interceptor.OpenAiResponseInterceptor;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.concurrent.TimeUnit;

@Configuration
public class OpenAiConfig {

    @Bean
    public OkHttpClient okHttpClient(final OkHttpProperties okHttpProperties) {
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(okHttpProperties.getProxy().getHost(), okHttpProperties.getProxy().getPort()));
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new OpenAILogger());
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                //自定义代理
                .proxy(proxy)
                //自定义日志输出
                .addInterceptor(httpLoggingInterceptor)
                //自定义返回值拦截
                .addInterceptor(new OpenAiResponseInterceptor())
                //自定义超时时间
                .connectTimeout(okHttpProperties.getTimeout(), TimeUnit.SECONDS)
                //自定义超时时间
                .writeTimeout(okHttpProperties.getTimeout(), TimeUnit.SECONDS)
                //自定义超时时间
                .readTimeout(okHttpProperties.getTimeout(), TimeUnit.SECONDS)
                .build();
        return okHttpClient;
    }

    @Bean
    public OpenAiClient openAiClient(final OkHttpClient okHttpClient,
                                     final OpenAiProperties openAiProperties) {
        return OpenAiClient.builder()
                .apiKey(openAiProperties.getAccessKey())
                .okHttpClient(okHttpClient)
                .build();
    }

    @Bean
    public OpenAiChatContext chatContext(final OpenAiProperties openAiProperties) {
        return new OpenAiChatContext(openAiProperties);
    }

}
